package netty.test4Chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class ChatClient {
    private final String host = "127.0.0.1";
    private final int port = 8000;
    private Selector selector;
    private SocketChannel socket;
    private String userName;

    /**
     * 完成初始化工作
     */
    public ChatClient() throws IOException {
        //1，获取selector
        selector = Selector.open();
        //2,连接 远程
        socket=SocketChannel.open(new InetSocketAddress("127.0.0.1", port));
        //3，配置成非阻塞
        socket.configureBlocking(false);
        //4，将channel 注册到selector 上
        socket.register(selector, SelectionKey.OP_READ);
        userName = socket.getLocalAddress().toString().substring(1);
        System.out.println(userName + "   is ok...");


    }

    /**
     * 客户端向服务器端发送消息
     *
     * @param msg
     */
    public void sendMessage(String msg) {
        msg = userName + " 说 " + msg;
        try {
            System.out.println("客户端准备发送消息start。。。");
            socket.write(ByteBuffer.wrap(msg.getBytes()));
            System.out.println("客户端准备发送消息end。。。");
        } catch (Exception e) {
            System.out.println("客户端准备发送消息异常。。。");
            e.printStackTrace();
        }
    }

    /**
     * 客户端读取服务器端发送的消息
     */
    public void read() {
        try {
            int count = selector.select();
            //1,count>0 说明有可用的通道了
            if (count > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    //2,从key 中取 通道
                    SelectionKey key = it.next();
                    if (key.isReadable()) {
                        SocketChannel socket = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        socket.read(buffer);
                        //3,把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println("客户端从服务器获取的数据为" + msg);
                    }
                    //处理完成后，当前的key 要删除，防止重复操作
                    it.remove();
                }

            } else {
               // System.out.println("没有可用的通道。。。"); //没有实际意义
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        final ChatClient client=new ChatClient();
        //1，从服务器读数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    client.read();
                    try{
                        //相当于每3s 从服务器端读一次数据
                        Thread.sleep(3000);
                    }catch (Exception e){

                    }
                }
            }
        }).start();

        //2，向服务器发送数据，这里从控制台发送
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
           client.sendMessage(s);
        }
    }
}
